<template>
  <div class="app-container checked">
    <div class="filter-container">
      <el-input v-model.trim="query.query.supplierName" clearable placeholder="请输入供应商名称" @keyup.enter.native="search" />
      <el-input v-model.trim="query.query.materialNo" clearable placeholder="请输入物料编号" @keyup.enter.native="search" />
      <el-select v-model="query.query.approveStatus" placeholder="请选择审核状态" clearable>
        <el-option v-for="item in orderState" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="search">{{
        $t("table.search")
      }}</el-button>
      <el-button type="primary" icon="el-icon-check" @click="handleClick(0)">通过</el-button>
      <el-button type="danger" icon="el-icon-close" @click="handleClick(1)">驳回</el-button>
    </div>
    <el-dialog title="OTC导入" width="400px" :visible.sync="importExportVisible">
      <div>
        <el-button type="text" @click="downloadExcel">下载模版</el-button>
        <el-upload ref="elUpload" drag :auto-upload="false" action="#" :limit="1" :on-change="handleChange"
          :on-remove="handleRemove">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importExportVisible = false">取 消</el-button>
        <el-button type="primary" @click="importExportSure">确 定</el-button>
      </span>
    </el-dialog>
    <el-table :data="tableData" highlight-current-row border @selection-change="handleSelectionChange"
      :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="purchaseOrderNumber" width="200" label="订单编号" fixed="left">
        <template slot-scope="{row}">
          <el-input v-model="row.purchaseOrderNumber" size="small" placeholder="请输入订单编号" />
        </template>
      </el-table-column>
      <el-table-column prop="saleOrderNum" label="销售订单数量" width="120" />
      <el-table-column prop="orderDate" label="下单日期">
        <template slot-scope="{ row: { orderDate } }">
          {{ getMoment(orderDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="supplierName" label="供应商名称" width="180px">
        <template slot-scope="{ row }">
          <el-select size="small" clearable v-model="row.supplierId" placeholder="请选择供应商"
            @change="handleSupplierName($event, row)">
            <el-option v-for="item in partnersList" :key="item.id" :label="item.partnerName" :value="item.id">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="物料编号" prop="material" />
      <el-table-column label="物料名称" prop="materialName" />
      <el-table-column prop="demandDate" label="需求日期">
        <template slot-scope="{ row: { demandDate } }">
          {{ getMoment(demandDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="orderedQty" label="订单数量">
        <template slot-scope="{ row }">
          <el-input v-model="row.orderedQty" onkeyup="value = value.match(/\d+(\.\d{0,4})?/)[0] || ''" size="small" placeholder="请输入订单数量" />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="未税单价" width="110">
        <template slot-scope="{ row }">
          <el-input v-model="row.price" onkeyup="value = value.match(/\d+(\.\d{0,4})?/)[0] || ''" size="small"
            placeholder="请输入未税单价" @change="handleInputPrice($event, row)" />
        </template>
      </el-table-column>
      <el-table-column prop="unitTaxedPrice" label="含税单价" width="110">
        <template slot-scope="{ row }">
          <el-input v-model="row.unitTaxedPrice" @change="handleUnitTaxedPrice($event, row)"
            onkeyup="value = value.match(/\d+(\.\d{0,4})?/)[0] || ''" size="small" placeholder="请输入含税单价" />
        </template>
      </el-table-column>
      <el-table-column prop="taxRateRounded" label="税率" width="110">
        <template slot-scope="{ row }">
          <el-input v-model="row.taxRateRounded" @change="handleTaxRateRounded($event, row)"
            onkeyup="value = value.match(/\d+(\.\d{0,4})?/)[0] || ''" size="small" placeholder="请输入税率">
            <i slot="suffix" style="line-height: 32px;">%</i>
          </el-input>
          <!-- {{ getTaxRate(row) }} -->
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="含税总价">
        <template slot-scope="{ row }">
          {{ multiply(row.orderedQty, row.unitTaxedPrice) }}
        </template>
      </el-table-column>
      <el-table-column prop="prepaidPayment" label="审批状态">
        <template slot-scope="{ row: { approveStatus } }">
          <el-tag v-if="approveStatus == 1" type="warning">待审核</el-tag>
          <el-tag v-else-if="approveStatus == 2" type="success">通过</el-tag>
          <el-tag v-else type="danger">驳回</el-tag>
        </template> </el-table-column>>
      <!-- <el-table-column :label="$t('table.actions')" fixed="right" width="150">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleSave(row)">保存</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
      @pagination="getInfo" />
  </div>
</template>
<script>
import {
  ordersApprovePageList,
  ordersApprovePass,
  ordersApproveReject,
  ordersModify
} from "@/api/weeklyStoragePlan";
import { codePartnersGetAll } from "@/api/invoice";
import moment from "moment";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { deepClone, downLoadTemplate } from "@/utils";
import math from "@/utils/math";
export default {
  name: "Productionplan",
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      multiply: math.multiply, //乘法
      subtract: math.subtract, //减法
      divide: math.divide, //除法
      add: math.add,//加法
      importExportForm: {},
      importExportVisible: false,
      orderState: [
        {
          label: "待审核",
          value: "1"
        },
        {
          label: "通过",
          value: "2"
        },
        {
          label: "驳回",
          value: "3"
        }
      ],
      inState: [
        {
          label: "未入库",
          value: "0"
        },
        {
          label: "部分入库",
          value: "1"
        },
        {
          label: "全部入库",
          value: "2"
        }
      ],
      q_z_formDate: [],
      type: 1,
      selectedList: [],
      selectedListData: [],
      total: 0,
      query: {
        pageSize: 10,
        pageIndex: 1,
        query: {}
      },
      tableData: [],
      checked: [],
      partnersList: []
    };
  },
  mounted() {
    this.getInfo();
    this.getCodePartnersGetAll();
  },
  methods: {
    handleInputPrice(e, item) {
      const { unitTaxedPrice, taxRateRounded } = item
      if (!Number(e) || (!Number(unitTaxedPrice) && !Number(taxRateRounded))) return
      if ((Number(unitTaxedPrice) && Number(taxRateRounded)) || Number(taxRateRounded)) {
        const unitTaxedPrice = this.multiply(Number(e), this.add(1, this.divide(Number(taxRateRounded), 100)))
        item.unitTaxedPrice = Number(unitTaxedPrice).toFixed(2)
        // item.unitTaxedPrice = Number(e) + (Number(e) * (Number(taxRateRounded) / 100))
      } else if (Number(unitTaxedPrice)) {
        const taxRateRounded = this.multiply(this.divide(this.subtract(Number(unitTaxedPrice), Number(e)), Number(e)), 100)
        item.taxRateRounded = Number(taxRateRounded).toFixed(2)
        // item.taxRateRounded = (Number(unitTaxedPrice) - Number(e)) / Number(e) * 100
      }
    },
    handleUnitTaxedPrice(e, item) {
      const { price, taxRateRounded } = item
      if (!Number(e) || (!Number(price) && !Number(taxRateRounded))) return
      if ((Number(price) && Number(taxRateRounded)) || Number(taxRateRounded)) {
        // item.price = Number(e) / (1 + Number(taxRateRounded))
        const price = this.divide(Number(e), this.add(1, this.divide(Number(taxRateRounded),100)))
        item.price = Number(price).toFixed(2)
      } else if (Number(price)) {
        // item.taxRateRounded = (Number(e) - Number(price)) / Number(price) * 100
        const taxRateRounded = this.multiply(this.divide(this.subtract(Number(e), Number(price)), Number(price)), 100)
        item.taxRateRounded = Number(taxRateRounded).toFixed(2)
      }
    },
    handleTaxRateRounded(e, item) {
      const { price, unitTaxedPrice } = item
      if (!Number(e) || (!Number(price) && !Number(unitTaxedPrice))) return
      if ((Number(price) && Number(unitTaxedPrice)) || Number(price)) {
        const unitTaxedPrice = this.multiply(Number(price), this.add(1, this.divide(Number(e), 100)))
        item.unitTaxedPrice = Number(unitTaxedPrice).toFixed(2)
        // item.unitTaxedPrice = Number(price) + (Number(price) * (Number(e) / 100))
      } else if (Number(unitTaxedPrice)) {
        const price = this.divide(Number(unitTaxedPrice), this.add(1, Number(e)))
        item.price = Number(price).toFixed(2)
        // item.price = Number(unitTaxedPrice) / (1 + Number(e))
      }
    },
    getTaxRate(row) {
      // const {unitTaxedPrice,price} = row
      // if(!unitTaxedPrice) return ''
      //return `${this.multiply(this.divide(this.subtract(unitTaxedPrice,price),unitTaxedPrice),100)}`
      const { unitTaxedPrice, price } = row;

      // 检查 unitTaxedPrice 和 price 是否存在且 price 不为零，以避免除以零的错误
      if (!unitTaxedPrice || !price) return "";

      // 计算税率（浮点数），注意这里使用 price 作为除数
      const taxRateFloat = ((unitTaxedPrice - price) / price) * 100;

      // 将税率四舍五入到两位小数（返回字符串），并添加百分比符号
      const taxRateRounded = taxRateFloat.toFixed(2);

      // 返回四舍五入后的税率字符串
      return `${taxRateRounded}%`;
    },
    getString(val) {
      if (!val) return "";
      if (val.indexOf(".") > -1) {
        return `${val.slice(0, val.indexOf("."), -1)}%`;
      } else {
        return `${val}%`;
      }
    },
    handleInput(val, row) {
      if (val.indexOf(".") != -1) {
        var str = val.substr(val.indexOf(".") + 1);
        if (str.indexOf(".") != -1) {
          val = val.substr(0, val.indexOf(".") + str.indexOf(".") + 1);
        }
      }
      row.unitTaxedPrice = val.replace(/[^\d^\.]+/g, "");
    },
    handleSupplierName(evt, item) {
      item.supplierName = this.partnersList.find(
        type => type.id == evt
      ).partnerName;
    },
    async getCodePartnersGetAll() {
      this.partnersList = await codePartnersGetAll({
        type: "2"
      });
    },
    getMoment(day) {
      if (!day) return "";
      return moment(day).format("YYYY-MM-DD");
    },
    async handleClick(val) {
      if (!this.selectedList.length) {
        this.$message.warning("请至少选择一条订单");
        return;
      }
      if (!this.selectedListData.every(type => type.approveStatus == 1)) {
        this.$message.warning("所选项包含非待审核状态，请重新选择！");
        return;
      }
      try {
        this.selectedListData.forEach(item => {
          const price = Number(item.price)
          const unitTaxedPrice = Number(item.unitTaxedPrice)
          if (!item.supplierId) {
            this.$message.warning("请选择供应商名称！");
            throw new Error();
          }
          if (!item.orderedQty) {
            this.$message.warning("请输入订单数量！");
            throw new Error();
          }
          if (!price) {
            this.$message.warning("请输入未税单价！");
            throw new Error();
          }
          if (!unitTaxedPrice) {
            this.$message.warning("请输入含税单价！");
            throw new Error();
          }
          if (unitTaxedPrice < price) {
            this.$message.warning("含税价格要大于未税价格！");
            throw new Error();
          }
        });
        const arr = [];
        this.selectedListData.forEach(item => {
          item.amount = this.multiply(item.orderedQty, Number(item.unitTaxedPrice));
          const p = new Promise(async resolve => {
            await this.handleSave(item);
            resolve();
          });
          arr.push(p);
        });
        Promise.all(arr).then(async () => {
          const httpFn = val === 0 ? ordersApprovePass : ordersApproveReject;
          await httpFn(this.selectedList.toString());
          this.$message.success("操作成功！");
          this.getInfo();
        });
      } catch (err) { }
    },
    async importExportSure() {
      try {
        if (!this.importExportForm.file) {
          this.$message.warning("请先上传商品数据");
          return false;
        }
        const formData = new FormData();
        for (let key in this.importExportForm) {
          formData.append(key, this.importExportForm[key]);
        }
        await orderImportOtc(formData);
        this.getInfo();
        this.$message.success("导入成功");
        this.importExportVisible = false;
      } catch (err) {
        this.handleRemove();
        this.$refs["elUpload"].clearFiles();
      }
    },
    handleChange(file, fileList) {
      this.importExportForm.file = file.raw;
    },
    handleRemove() {
      this.importExportForm.file = "";
    },
    downloadExcel() {
      downLoadTemplate("OTC导入模版.xlsx", "OTCtemplate.xlsx");
    },
    importExport() {
      this.importExportVisible = true;
    },
    // handleCLick(id) {
    //   this.$confirm('确认删除?', '警告', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(async () => {
    //     await orderDel(id)
    //     this.getInfo()
    //     this.$message.success('删除成功!')
    //   })
    // },
    async handleSave(row) {
      await ordersModify(row);
    },
    q_z_selectTime(value1) {
      if (value1) {
        this.query.query.planDeliverDateBegin = value1[0];
        this.query.query.planDeliverDateEnd = value1[1];
      } else {
        this.query.query.planDeliverDateBegin = "";
        this.query.query.planDeliverDateEnd = "";
      }
    },
    handleSelectionChange(e) {
      this.selectedList = [];
      this.selectedListData = [];
      this.checked = e;
      e.forEach(item => {
        this.selectedList.push(item.id);
        this.selectedListData.push(item);
      });
    },
    async getInfo() {
      const { records, total } = await ordersApprovePageList(this.query);
      records.forEach(item => {
        if (!item.unitTaxedPrice || !item.price) {
          this.$set(item, 'taxRateRounded', 13)
        } else {
          // 计算税率（浮点数），注意这里使用 price 作为除数
          const taxRateFloat = ((item.unitTaxedPrice - item.price) / item.price) * 100;
          // 将税率四舍五入到两位小数（返回字符串），并添加百分比符号
          const taxRateRounded = taxRateFloat.toFixed(2);
          this.$set(item, 'taxRateRounded', taxRateRounded)
        }
      })
      this.tableData = records;
      this.total = total;
    },
    search() {
      this.query.pageIndex = 1;
      this.getInfo();
    }
  }
};
</script>
